<template>
    <div>
        <div>
            <el-form-item label="项目类别" style="width:300px">
                <el-select v-model="category" placeholder="请选择" filterable @change="getPlugins">
                    <el-option v-for="item in categories" :key="item.id" :label="item.name" :value="item.id!" />
                </el-select>
            </el-form-item>
            <el-button type="primary" @click="handleAdd" :disabled="!category">新增插件</el-button>
        </div>
        <el-table :data="plugins" class="main-table" border stripe size="small" height="calc(100vh - 246px)">
            <el-table-column prop="name" label="名称" min-width="120" align="center" />
            <el-table-column prop="command" label="安装命令" min-width="200" />
            <el-table-column prop="description" label="描述" min-width="150" />
            <el-table-column prop="created_at" label="创建时间" width="175" align="center" />
            <el-table-column label="操作" width="100" align="center" fixed="right">
                <template #default="{ row }">
                    <div class="operate">
                        <el-link type="primary" @click="handleEdit(row)" :underline="false">编辑</el-link>
                        <el-link type="danger" @click="handleDelete(row.id)" :underline="false">删除</el-link>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination background :page-sizes="[10, 20, 50]" @change="pageChange"
            layout="total, prev, pager, next, sizes" :total="total" />

        <el-drawer v-model="drawer" direction="rtl" size="300" :before-close="resetForm" :show-close="true"
            :wrapperClosable="true">
            <el-form :model="form" ref="plugins-form" :rules="rules" label-width="80px" :inline="false">
                <el-form-item label="插件名称" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="安装命令" prop="command">
                    <el-input v-model="form.command"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input v-model="form.description"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">保存</el-button>
                    <el-button @click="resetForm">取消</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
import database from '@/api/database'
import { ElMessage } from 'element-plus'


const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const drawer = ref(false)
const categories = ref<Category[]>([])
const category = ref()
const plugins = ref<PluginType[]>()
const form = ref<PluginType>({ name: '', description: '', command: '', category_id: 0 })
const rules = reactive({
    name: [
        { required: true, message: '请输入名称', trigger: 'blur' },
        { min: 1, max: 20, message: '长度在20个字符内', trigger: 'blur' },
    ],
    description: [
        { min: 1, max: 50, message: '长度在50个字符内', trigger: 'blur' },
    ],
    command: [
        { required: true, message: '请输入命令', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在50个字符内', trigger: 'blur' },
    ],
})
const pluginsForm = useTemplateRef('plugins-form')

async function getPlugins() {
    (await database()).table('plugins').where('category_id', category.value).paginate<PluginType>(page.value, pageSize.value).then(res => {
        plugins.value = res.data
        total.value = res.total
    }).catch(err => {
        category.value = undefined
        ElMessage.error(err)
    })
}
function handleEdit(row: Command) {
    form.value = { ...row }
    drawer.value = true
}
async function handleDelete(id: number) {
    (await database()).table('plugins').delete(id).then(res => {
        if (res == 1) {
            ElMessage.success('删除成功')
            getPlugins()
        } else {
            ElMessage.error('没有数据被删除')
        }
    }).catch(err => {
        ElMessage.error(err)
    })
}
function onSubmit() {
    pluginsForm.value?.validate(async (valid: boolean) => {
        if (valid) {
            if (form.value?.id) {
                // 更新
                (await database()).table('plugins').where('id', form.value.id).update(form.value).then(() => {
                    resetForm()
                    getPlugins()
                    ElMessage.success('更新成功')
                }).catch(err => {
                    ElMessage.error(err)
                })
            } else {
                (await database()).table('plugins').create(form.value).then(() => {
                    resetForm()
                    getPlugins()
                    ElMessage.success('操作成功')
                }).catch(err => {
                    ElMessage.error(err)
                })
            }
        }
    })
}
function pageChange(p: number, ps: number) {
    page.value = p
    pageSize.value = ps
    getPlugins()
}
function resetForm() {
    pluginsForm.value?.resetFields()
    drawer.value = false
}
function handleAdd() {
    form.value = { name: '', description: '', command: '', category_id: category.value }
    drawer.value = true
}

onMounted(async () => {
    (await database()).table('categories').all<Category>().then(res => {
        categories.value = res
    }).catch(err => {
        ElMessage.error(err)
    })
})
</script>

<style lang="scss" scoped></style>